from django.contrib.syndication.views import Feed
from python.infoer.models import SPS
from django.utils.feedgenerator import Rss201rev2Feed
from django.template import Context, loader
from django.http import HttpResponse
from django.contrib.sites.models import Site

class SPSFeedGenerator(Rss201rev2Feed):
    def add_root_elements(self, handler):
        super(SPSFeedGenerator, self).add_root_elements(handler)
		
	def add_item_elements(self, handler, item):
		 super(SPSFeedGenerator, self).add_item_elements(handler)

class SPSBaseFeed(Feed):
	title = "SPS"
	feed_type = SPSFeedGenerator
	link = "/"
	description = "SPS distribution RSS"
	
	def items(self):
		return None
	
	def item_title(self, item):
		if item.type in ['TCP', 'UDP']:
			return "%s:%i" % (item.ip_address, item.port)
		elif item.type in ['HTTP', 'HTTPS']:
			return item.url
		else:
			return "Server error. Unknown SPS type"
	
	def item_description(self, item):
		if item.type in ['TCP', 'UDP']:
			t = loader.get_template("feed_socket_content.html")
			c = Context({
			'ip_address': item.ip_address,
			'port' : item.port,
			'type' : item.type,
			'host' : Site.objects.get_current().domain,
			'id' : item.id,
			})
			return t.render(c)
		elif item.type in ['HTTP', 'HTTPS']:
			t = loader.get_template("feed_url_content.html")
			c = Context({
			'url': item.url,
			'type' : item.type,
			'host' : Site.objects.get_current().domain,
			'id' : item.id,
			})
			return t.render(c)
		else:
			return "Server error. Unknown SPS type"
		
	def item_link(self, item):
		return ""

class SPSFeedLatest(SPSBaseFeed):
	def items(self):
		return SPS.objects.order_by('last_update_date')[:10]
		
class SPSFeedSocket(SPSBaseFeed):
	def items(self):
		return SPS.objects.filter(type__in=['TCP', 'UDP']).order_by('last_update_date')[:10]
				
class SPSFeedHTTP(SPSBaseFeed):
	def items(self):
		return SPS.objects.filter(type='HTTP').order_by('last_update_date')[:10]
		
class SPSFeedHTTPS(SPSBaseFeed):
	def items(self):
		return SPS.objects.filter(type='HTTPS').order_by('last_update_date')[:10]

class SPSFeedTCP(SPSBaseFeed):
	def items(self):
		return SPS.objects.filter(type='TCP').order_by('last_update_date')[:10]
		
class SPSFeedUDP(SPSBaseFeed):
	def items(self):
		return SPS.objects.filter(type='UDP').order_by('last_update_date')[:10]